/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.browser;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.*;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.webapp.taglib.core.grid.util.FilterConditions;
import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;
import com.blandware.atleap.webapp.taglib.core.grid.util.StringFilter;
import com.blandware.atleap.webapp.util.core.VirtualFolder;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.oro.text.regex.*;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>Returns browser page with allows to select a content page
 * </p>
 * <p><a href="CallCreateActionPageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.31 $ $Date: 2007/12/19 12:49:51 $
 * @struts.action path="/core/browser/browseContentPages"
 * validate="false"
 * roles="core-browser-contentPage"
 * @struts.action-forward name="showBrowser"
 * path=".core.browser.cpBrowser"
 */
public final class BrowseContentPagesAction extends BaseBrowserAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        boolean opening = getOpening(request);
        String modeToRequest = WebappConstants.BROWSER_MODE_LINKS;
        if (!GenericValidator.isBlankOrNull(request.getParameter("mode"))) {
            modeToRequest = request.getParameter("mode");
        }
        String mode = processOpeningAndGetMode(opening, session,
                                               modeToRequest, WebappConstants.BROWSER_MODE_LINKS);

        // computing name of menu
        computeMenuNameAndSaveToRequest(mode, request);

        // check for locale suffix
		String localeSuffix;
		if ( !GenericValidator.isBlankOrNull(request.getParameter("editorAreaLanguage")) ) {
			localeSuffix = request.getParameter("editorAreaLanguage");
			session.setAttribute(WebappConstants.BROWSER_LOCALE_SUFFIX_KEY, localeSuffix);
		} else {
			localeSuffix = (String) session.getAttribute(WebappConstants.BROWSER_LOCALE_SUFFIX_KEY);
		}

		String currentFolder = "";
		if ( request.getParameter("currentFolder") != null ) {
			currentFolder = request.getParameter("currentFolder");
			session.setAttribute(WebappConstants.CONTENT_PAGES_CURRENT_PATH_KEY, currentFolder);
		} else if ( session.getAttribute(WebappConstants.CONTENT_PAGES_CURRENT_PATH_KEY) != null ) {
			currentFolder = (String) session.getAttribute(WebappConstants.CONTENT_PAGES_CURRENT_PATH_KEY);
		}

		if ( currentFolder == null || currentFolder.equals("/") ) {
			currentFolder = "";
		}

		// ensure, that current folder starts with slash and does not end with slash
		if ( currentFolder.length() > 0 ) {
			if ( !currentFolder.startsWith("/") ) {
				currentFolder = "/" + currentFolder;
			}
			if ( currentFolder.endsWith("/") ) {
				currentFolder = currentFolder.substring(0, currentFolder.length() - 1);
			}
		}

		// get all content pages, which exist in current folder

		StringFilter uriFilter = new StringFilter("page.uri");
		uriFilter.createFirstClause(FilterConditions.STRING_STARTS_WITH, WebappConstants.CONTENT_PAGES_URI_PREFIX + currentFolder + "/");

		Grid cpGrid = getGridByName(WebappConstants.BROWSER_CONTENT_PAGES_GRID, session);
		if ( cpGrid == null ) {
			cpGrid = new Grid(WebappConstants.BROWSER_CONTENT_PAGES_GRID);
		}

		cpGrid.addFilter(uriFilter);

		saveGrid(cpGrid, session);

		QueryInfo queryInfo = new QueryInfo();
		queryInfo.setWhereClause(cpGrid.getWhereClause());

		Map queryParameters = new HashMap();
		Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
		queryParameters.put("localeIdentifier", locale.getLanguage());
		queryInfo.setQueryParameters(queryParameters);

		PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
		PartialCollection contentPages = pageManager.listContentPages(queryInfo);

		// we have list of content pages which are all placed in current folder
		// we only need to divide acquired set to subfolders and pages
		// we need regular expression in order to do it:
		String folderPatternString = "(" + RegExUtil.escapeMetasymbols(WebappConstants.CONTENT_PAGES_URI_PREFIX + currentFolder) + ")";

		folderPatternString += "\\/([^\\/]+)(\\/[^\\/]+)+";

		// pattern compiler instance to use
		PatternCompiler compiler = new Perl5Compiler();

		// compiled patterns
		Pattern folderPattern = compiler.compile(folderPatternString);

		// pattern matcher instance to use
		PatternMatcher matcher = new Perl5Matcher();

		// list of folders
		SortedSet folderSet = new TreeSet();

		// list of pages
		List pages = new ArrayList();

		for ( Iterator i = contentPages.iterator(); i.hasNext(); ) {
			ContentPage contentPage = (ContentPage) i.next();
			String uri = contentPage.getUri();

			// check folder name
			if ( matcher.matches(uri, folderPattern) ) {
				MatchResult result = matcher.getMatch();

				// according to pattern, folder name is in second group
				Folder folder = new VirtualFolder(result.group(2), currentFolder, '/');
				folderSet.add(folder);

			} else {
				// add page to list
				ContentPage tmp = new ContentPage();
				WebappUtil.copyProperties(tmp, contentPage, request);
				String tmpUri = WebappUtil.getActionMappingURL(uri, null, request, WebappConstants.URL_TYPE_CONTEXT_RELATIVE, localeSuffix);
				if ( tmpUri.startsWith("/") ) {
					tmpUri = tmpUri.substring(1);
				}
				tmp.setUri(tmpUri);
				pages.add(tmp);
			}
		}

		// create parent folder if current folder is not the root folder
		Folder parentFolder = null;
		if ( currentFolder.length() > 0 ) {
			int k = currentFolder.lastIndexOf("/");
			if ( k < 0 ) {
				k = 0;
			}
			String parentFolderPath = currentFolder.substring(0, k);
			parentFolder = new VirtualFolder("..", parentFolderPath, '/', true);
		}

		LinkedList folders = new LinkedList(folderSet);
		if ( parentFolder != null ) {
			folders.addFirst(parentFolder);
		}

        if (opening) {
            String inputId = request.getParameter("inputId");
            if ( inputId != null && inputId.length() != 0 ) {
                session.setAttribute(WebappConstants.HTML_INPUT_TAG_ID_KEY, inputId);
            } else {
                session.removeAttribute(WebappConstants.HTML_INPUT_TAG_ID_KEY);
            }
        }

        request.setAttribute(WebappConstants.CONTENT_PAGES_COLLECTION_KEY, pages);
		request.setAttribute(WebappConstants.FOLDERS_COLLECTION_KEY, folders);

		request.setAttribute(WebappConstants.CURRENT_PATH_KEY, new FolderList(VirtualFolder.splitPath(currentFolder)));

		return mapping.findForward("showBrowser");
	}

}